package cn.itcast.usercontext.interceptor;

import cn.itcast.usercontext.util.JwtUtil;
import cn.itcast.usercontext.util.usersession.LoginUser;
import cn.itcast.usercontext.util.usersession.UserContext;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sxt
 * @version 1.0
 * @description 用户上下文拦截器
 * @date 2024/4/24 23:02
 */
public class UserContextInterceptor implements HandlerInterceptor {

    @Autowired
    private ILoginUser loginUser;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String userToken;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("user-token".equals(cookie.getName())) {
                    userToken = cookie.getValue();
                    Claims claims;
                    try {
                        claims = JwtUtil.verifyToken(userToken);
                    } catch (Exception e) {
                        return true;
                    }
                    // 获取了userId
                    String userId = claims.getId();

                    // 获取用户信息
                    LoginUser user = loginUser.getLoginUser(Long.parseLong(userId));

                    // 存入缓存
                    if (user != null) {
                        UserContext.put(user);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除当前用户 防止内存泄漏
        UserContext.remove();
    }
}
